package com.java.code.zookeeper.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author weichuanyuan
 * @e-mail wei.cy@bsoft.com.cn
 * @date 2021/10/19 9:19
 * @package com.java.code.zookeeper.curator
 * @description
 */
@Configuration
@ConditionalOnProperty(name = "spring.zookeeper.enabled", havingValue = "true")
public class CuratorConfig {
    @Value("${spring.zookeeper.url}")
    private String connectString;
    @Value("${spring.zookeeper.timeout}")
    private int timeout;
    @Value("${spring.zookeeper.authority}")
    private String authority;

    @Bean(name = "curatorFramework")
    public CuratorFramework curatorFramework() {
        CuratorFramework client = null;
        try {
            CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
                    .connectString(connectString)
                    .retryPolicy(new RetryNTimes(1, 1000))
                    .connectionTimeoutMs(timeout);
            if (authority != null && authority.length() > 0) {
                builder = builder.authorization("digest", authority.getBytes());
            }
            client = builder.build();
//            client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
//                @Override
//                public void stateChanged(CuratorFramework client, ConnectionState state) {
//                    if (state == ConnectionState.LOST) {
//                        System.out.println("当前状态失去链接");
//                    } else if (state == ConnectionState.CONNECTED) {
//                        System.out.println("当前状态已链接");
//                    } else if (state == ConnectionState.RECONNECTED) {
//                        System.out.println("当前状态重新链接");
//                    }
//                }
//            });
            client.start();
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
        return client;
    }
}
